import { defineStore } from 'pinia'
import { useUserStore } from '@/stores/user'

export const useWebsocketStore = defineStore('websocket', {
    state: () => ({
        socket: null,
        connected: false,
        baseUrl: 'ws://127.0.0.1:8080/websocket',
        pk: {
            status: 'matching',
            opponents: [],
            roomId: null,
        },
    }),
    actions: {
        connect(url) {
            if (this.socket && this.connected) {
                return
            }
            try {
                this.socket = new WebSocket(url)

                this.socket.onopen = () => {
                    this.connected = true
                    console.log('WebSocket连接成功')
                }

                this.socket.onclose = () => {
                    this.connected = false
                    console.log('WebSocket连接关闭')
                }

                this.socket.onerror = (error) => {
                    console.error('WebSocket连接错误:', error)
                }
            } catch (error) {
                console.error('WebSocket连接错误:', error)
            }
        },
        initConnection() {
            const userStore = useUserStore()
            if (userStore.is_login && userStore.token) {
                const wsUrl = `${this.baseUrl}/${userStore.token}`
                this.connect(wsUrl)
            } else {
                console.log('用户未登录，不建立WebSocket连接')
            }
        },
        // 用户登录后调用此方法连接WebSocket
        connectAfterLogin(token) {
            // 确保有token
            if (!token) {
                const userStore = useUserStore()
                token = userStore.token
            }

            if (token) {
                const wsUrl = `${this.baseUrl}/${token}`
                this.connect(wsUrl)
            } else {
                console.error('无法建立WebSocket连接：缺少token')
            }
        },
        disconnect() {
            if (this.socket) {
                this.socket.close
                this.socket = null
                this.connected = false
                console.log('WebSocket连接已关闭')
            }
        },
        updateSocket(socket) {
            this.socket = socket
        },
        updateOpponents(opponents) {
            this.pk.opponents = opponents
        },
        updateStatus(status) {
            this.pk.status = status
        },
        updateRoomId(roomId) {
            this.pk.roomId = roomId
        },
    },
})
